package service

import (
	"crypto/sha256"
	"encoding/hex"
	"encoding/json"
	"fmt"
	"strconv"
	"time"
	"cmsapi/src/lib"
	"cmsapi/src/model"

	"github.com/gin-gonic/gin"
)

//查询一条数据
func One2(c *gin.Context) {
	//lib.Check(c)
	//fmt.Println(s)
	where, like := lib.Get(c)

	fmt.Println("Login2222", where, like)
}
func Login(c *gin.Context) {
	lib.SysStartTime = time.Now().UnixNano() / int64(time.Millisecond) //初始化时间
	fmt.Println("Login Start")
	//	where, like := lib.Get(c)

	where := make(map[string]interface{})
	where["user_name"] = c.Query("user_name") //).(string)
	where["password"] = c.Query("password")   //).(string)
	//	wheredata, _ := json.Marshal(where)
	//	c.Set("wheredata", string(wheredata))
	//fmt.Printf("密码  : %s=>%T \r\n", where["password"], where["password"])

	if where["user_name"] == "" || where["password"] == "" {
		c.Set("code", 981) //用户名或密码不存在
		c.Next()
	}

	//data := make(map[string]interface{})
	var user model.UserModel
	//id := where["id"]
	//fmt.Printf("data %T=>%s \r\n\r\n", data, len(data))
	if where["user_name"] != nil {
		rel := lib.Mysql.Debug().Table(lib.DbInfo.Prefix + "user").Select("*") //.Where(where)
		name := (where["user_name"]).(string)
		rel.Where("user_name = ? or phone=? or email=?", name, name, name)

		//rel.Where("user_name LIKE ?", "%"+((where["user_name"]).(string))+"%")
		rel.Find(&user)
	}
	//	fmt.Printf("user %s /r/n ", user)
	if user.ID == 0 { //|| len(user) == 0
		c.Set("code", 988) //用户不存在
		c.Next()
		//fmt.Println("登录用户不存在", (where["user_name"]).(string))
	} else {
		//fmt.Printf("登录密码 data : %s=>%T  where:%s=>%T \r\n", (data["password"]).(string), (data["password"]).(string), (where["password"]).(string), (where["password"]).(string))
		if user.Password != (where["password"]).(string) {
			c.Set("code", 989) //密码错误
			c.Next()
		} else {
			idstring := strconv.FormatInt(user.ID, 10)
			jsontoken, _ := lib.RedisGet("login:user:id:" + idstring) //, (token["token"]).(string), 10
			//fmt.Printf("jsontoken %s /r/n", jsontoken)
			if jsontoken == "" {
				//fmt.Printf("ID data : %s=>%T  \r\n", strconv.Itoa(int((data["id"]).(int32))), strconv.Itoa(int((data["id"]).(int32))))
				//	fmt.Println("成功281")
				//生成token
				token := make(map[string]interface{})
				//token["lasttimestamp"] = time.Now().Format("2006-01-02 15:04:05")
				token["lasttimestamp"] = time.Unix((time.Now().Unix() + 3600), 0).Format("2006-01-02 15:04:05")
				//intjson, _ := json.Marshal(data["id"])
				//	k := strconv.Itoa((data["id"]).(int)) + (token["_timestamp"]).(string) + "JT.Z"
				k := idstring + (token["lasttimestamp"]).(string) + "JT.Z"
				h := sha256.New()

				h.Write([]byte(k))
				token["token"] = hex.EncodeToString(h.Sum(nil))
				//	fmt.Printf("ID data : %s=>%T  \r\n", token["token"], token["token"])

				redisKey := "login:user:token:" + ((token["token"]).(string))
				//	token["redisKey"] = redisKey
				//	d1, _ := json.Marshal(data)
				rel, _ := lib.RedisSet(redisKey, user, 3600)
				fmt.Printf("redis rel : %s=>%T  \r\n", rel, rel)
				if rel == "OK" {
					jsondata, _ := json.Marshal(token)
					c.Set("jsondata", string(jsondata))
					//	fmt.Printf("jsondata %s /r/n", string(jsondata))
					lib.RedisSet("login:user:id:"+idstring, token, 600) //data.id redis缓存
				}
				//写入日志
				model.LogCreate(c, lib.Mysql, map[string]interface{}{"type": "login", "method": "get", "token": token["token"]})
			} else {

				c.Set("jsondata", jsontoken)
			}
			c.Set("code", 201) //成功
			c.Next()
		}

	}
	/*
		for k, v := range data {
			//fmt.Printf("\r\n vvvvvvvvvv %s=>%T %s", v, v, k)
			atime := (v["add_time"]).(int64)
			//	datatime := time.Unix(atime, 0).Format("2006-01-02 15:04:05")
			//	data[k]["add_time"] = datatime
			//	delete(data[k], "user_id")
			//	delete(data[k], "ip")
		}
	*/
	//	fmt.Printf("Loginwhere %s=>%T \r\n", where["user_name"], where["user_name"])
	//	fmt.Println("Login", data, where)
	/*
		c.Set("code", 202)

		jsondata, _ := json.Marshal(data)

		c.Set("jsondata", string(jsondata))

		wheredata, _ := json.Marshal(where)
		c.Set("wheredata", string(wheredata))
		c.Next()
	*/
	//	return

	//c.Set("code", 201)
	//c.Next()

}
